﻿package net.wangit.framework.expression;

import net.wangit.context.ActionContext;
import net.wangit.user.org.Org;
import net.wangit.user.org.OrgFactory;
import net.wangit.util.Checker;
import net.wangit.util.StringUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 机构表达式
 * @author watson
 *
 */
public class OrgExpression {

	private static final Log log = LogFactory
			.getLog(net.wangit.framework.expression.OrgExpression.class);
	private static final String PREFIX = "$O{";
	private static final String SUFFIX = "}";

	public OrgExpression() {
	}

	public static final String resolve(ActionContext ac, String expression) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression, OrgExpression.PREFIX,
				OrgExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					OrgExpression.PREFIX)).append(attribute).append(
					OrgExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(ac, attribute));
			expression = expression.substring(index + attribute.length()
					+ OrgExpression.PREFIX.length()
					+ OrgExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	private static String getValue(ActionContext ac, String attribute) {
		String orgId = ac.getVisitor().getUser().getOrgId();
		String value;
		try {
			Org org = OrgFactory.getOrg(orgId);
			value = null;
			if (org != null)
				value = org.get(attribute);
			return value != null ? value : "";
		} catch (Exception e) {
			log.error(e);
			return "";
		}
	}

}
